#include "viml/gc_statistics.h"
#include "viml/garbage_collector.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <numeric>

namespace viml {

// GCStatisticsCollector实现
GCStatisticsCollector::GCStatisticsCollector()
    : start_time_(std::chrono::high_resolution_clock::now())
    , last_collection_time_(start_time_) {

    // 预分配历史存储
    collection_history_.reserve(1000);
    root_set_stats_.root_count_history.reserve(RootSetStats::MAX_HISTORY_SIZE);
    root_set_stats_.timestamp_history.reserve(RootSetStats::MAX_HISTORY_SIZE);
}

GCStatisticsCollector::CollectionCycle* GCStatisticsCollector::start_collection_cycle(
    CollectionCycle::TriggerReason reason, bool is_incremental) {

    std::lock_guard<std::mutex> lock(stats_mutex_);

    auto cycle = std::make_unique<CollectionCycle>();
    cycle->start_time = std::chrono::high_resolution_clock::now();
    cycle->trigger_reason = reason;
    cycle->is_incremental = is_incremental;

    CollectionCycle* cycle_ptr = cycle.get();

    if (is_incremental) {
        incremental_cycles_.push_back(cycle_ptr);
    } else {
        // 完全GC，清理未完成的增量收集
        incremental_cycles_.clear();
    }

    // 记录堆大小（收集前）
    cycle->heap_size_before = allocation_stats_.current_bytes_allocated;

    collection_history_.push_back(std::move(cycle));

    return cycle_ptr;
}

void GCStatisticsCollector::finish_collection_cycle(CollectionCycle* cycle) {
    if (!cycle) return;

    std::lock_guard<std::mutex> lock(stats_mutex_);

    cycle->end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
        cycle->end_time - cycle->start_time);
    cycle->duration_ms = duration.count() / 1000.0;

    // 记录堆大小（收集后）
    cycle->heap_size_after = allocation_stats_.current_bytes_allocated;
    cycle->heap_size_freed = cycle->heap_size_before - cycle->heap_size_after;

    // 更新性能统计
    update_performance_stats();

    // 从增量收集列表中移除
    auto it = std::find(incremental_cycles_.begin(),
                        incremental_cycles_.end(), cycle);
    if (it != incremental_cycles_.end()) {
        incremental_cycles_.erase(it);
    }

    last_collection_time_ = cycle->end_time;
}

GCStatisticsCollector::CollectionCycle* GCStatisticsCollector::get_current_cycle() const {
    std::lock_guard<std::mutex> lock(stats_mutex_);

    // 返回最新的收集周期
    if (!collection_history_.empty()) {
        return collection_history_.back().get();
    }

    // 检查增量收集
    if (!incremental_cycles_.empty()) {
        return incremental_cycles_.back();
    }

    return nullptr;
}

// 标记阶段统计
void GCStatisticsCollector::record_mark_phase_start(CollectionCycle* cycle) {
    if (!cycle) return;

    std::lock_guard<std::mutex> lock(stats_mutex_);
    cycle->mark_phase_ms = std::chrono::duration_cast<std::chrono::microseconds>(
        std::chrono::high_resolution_clock::now() - cycle->start_time).count() / 1000.0;
}

void GCStatisticsCollector::record_mark_phase_end(CollectionCycle* cycle) {
    if (!cycle) return;

    std::lock_guard<std::mutex> lock(stats_mutex_);
    auto now = std::chrono::high_resolution_clock::now();
    cycle->mark_phase_ms = std::chrono::duration_cast<std::chrono::microseconds>(
        now - cycle->start_time).count() / 1000.0;
}

void GCStatisticsCollector::record_object_marked(CollectionCycle* cycle) {
    if (!cycle) return;

    std::lock_guard<std::mutex> lock(stats_mutex_);
    cycle->objects_marked++;
}

void GCStatisticsCollector::record_root_marked(CollectionCycle* cycle) {
    if (!cycle) return;

    std::lock_guard<std::mutex> lock(stats_mutex_);
    cycle->roots_marked++;
}

void GCStatisticsCollector::record_worklist_processed(CollectionCycle* cycle, size_t count) {
    if (!cycle) return;

    std::lock_guard<std::mutex> lock(stats_mutex_);
    cycle->worklist_processed += count;
}

// 清除阶段统计
void GCStatisticsCollector::record_sweep_phase_start(CollectionCycle* cycle) {
    if (!cycle) return;

    std::lock_guard<std::mutex> lock(stats_mutex_);
    auto now = std::chrono::high_resolution_clock::now();
    cycle->sweep_phase_ms = std::chrono::duration_cast<std::chrono::microseconds>(
        now - cycle->start_time).count() / 1000.0;
}

void GCStatisticsCollector::record_sweep_phase_end(CollectionCycle* cycle) {
    if (!cycle) return;

    std::lock_guard<std::mutex> lock(stats_mutex_);
    auto now = std::chrono::high_resolution_clock::now();
    cycle->sweep_phase_ms = std::chrono::duration_cast<std::chrono::microseconds>(
        now - cycle->start_time).count() / 1000.0;
}

void GCStatisticsCollector::record_object_swept(CollectionCycle* cycle, size_t bytes) {
    if (!cycle) return;

    std::lock_guard<std::mutex> lock(stats_mutex_);
    cycle->objects_swept++;
    cycle->bytes_swept += bytes;
}

// 内存统计
void GCStatisticsCollector::record_allocation(const std::string& type, size_t size) {
    if (!config_.enable_allocation_tracking) return;

    std::lock_guard<std::mutex> lock(stats_mutex_);

    allocation_stats_.total_allocations++;
    allocation_stats_.current_allocations++;
    allocation_stats_.total_bytes_allocated += size;
    allocation_stats_.current_bytes_allocated += size;

    // 更新峰值统计
    if (allocation_stats_.current_allocations > allocation_stats_.peak_allocations) {
        allocation_stats_.peak_allocations = allocation_stats_.current_allocations;
    }

    if (allocation_stats_.current_bytes_allocated > allocation_stats_.peak_bytes_allocated) {
        allocation_stats_.peak_bytes_allocated = allocation_stats_.current_bytes_allocated;
    }

    // 类型统计
    if (type == "string") {
        allocation_stats_.string_allocations++;
    } else if (type == "list") {
        allocation_stats_.list_allocations++;
    } else if (type == "dict") {
        allocation_stats_.dict_allocations++;
    } else if (type == "function") {
        allocation_stats_.function_allocations++;
    } else {
        allocation_stats_.other_allocations++;
    }

    // 大小统计
    if (size < allocation_stats_.min_object_size) {
        allocation_stats_.min_object_size = size;
    }
    if (size > allocation_stats_.max_object_size) {
        allocation_stats_.max_object_size = size;
    }

    // 更新平均大小
    if (allocation_stats_.total_allocations > 0) {
        allocation_stats_.avg_object_size =
            static_cast<double>(allocation_stats_.total_bytes_allocated) /
            allocation_stats_.total_allocations;
    }
}

void GCStatisticsCollector::record_deallocation(const std::string& type, size_t size) {
    if (!config_.enable_allocation_tracking) return;
    (void)type; // 避免未使用参数警告

    std::lock_guard<std::mutex> lock(stats_mutex_);

    allocation_stats_.total_deallocations++;
    if (allocation_stats_.current_allocations > 0) {
        allocation_stats_.current_allocations--;
    }

    if (allocation_stats_.current_bytes_allocated >= size) {
        allocation_stats_.current_bytes_allocated -= size;
    }

    allocation_stats_.total_bytes_freed += size;
}

void GCStatisticsCollector::record_heap_size(size_t size) {
    std::lock_guard<std::mutex> lock(stats_mutex_);
    allocation_stats_.current_bytes_allocated = size;
}

// 根集统计
void GCStatisticsCollector::record_root_set_stats(const RootSetStats& stats) {
    if (!config_.enable_root_set_tracking) return;

    std::lock_guard<std::mutex> lock(stats_mutex_);
    root_set_stats_ = stats;

    // 更新历史
    root_set_stats_.root_count_history.push_back(stats.total_roots);
    root_set_stats_.timestamp_history.push_back(std::chrono::high_resolution_clock::now());

    // 限制历史大小
    if (root_set_stats_.root_count_history.size() > RootSetStats::MAX_HISTORY_SIZE) {
        root_set_stats_.root_count_history.erase(root_set_stats_.root_count_history.begin());
        root_set_stats_.timestamp_history.erase(root_set_stats_.timestamp_history.begin());
    }
}

void GCStatisticsCollector::record_root_operation(double operation_time_us,
                                          bool is_batch, bool is_duplicate) {
    if (!config_.enable_root_set_tracking) return;

    std::lock_guard<std::mutex> lock(stats_mutex_);

    if (is_batch) {
        root_set_stats_.batch_operations++;
    }

    if (is_duplicate) {
        root_set_stats_.duplicate_removals++;
    }

    // 更新平均操作时间（简单移动平均）
    static const double ALPHA = 0.1; // 平滑因子
    if (root_set_stats_.avg_add_time_us == 0.0) {
        root_set_stats_.avg_add_time_us = operation_time_us;
    } else {
        root_set_stats_.avg_add_time_us =
            ALPHA * operation_time_us + (1.0 - ALPHA) * root_set_stats_.avg_add_time_us;
    }
}

// 获取统计信息
GCStatisticsCollector::AllocationStats GCStatisticsCollector::get_allocation_stats() const {
    std::lock_guard<std::mutex> lock(stats_mutex_);
    return allocation_stats_;
}

GCStatisticsCollector::PerformanceStats GCStatisticsCollector::get_performance_stats() const {
    std::lock_guard<std::mutex> lock(stats_mutex_);
    return performance_stats_;
}

GCStatisticsCollector::RootSetStats GCStatisticsCollector::get_root_set_stats() const {
    std::lock_guard<std::mutex> lock(stats_mutex_);
    return root_set_stats_;
}

const std::vector<std::unique_ptr<GCStatisticsCollector::CollectionCycle>>& GCStatisticsCollector::get_collection_history() const {
    std::lock_guard<std::mutex> lock(stats_mutex_);
    return collection_history_;
}

size_t GCStatisticsCollector::get_collection_count() const {
    std::lock_guard<std::mutex> lock(stats_mutex_);
    return collection_history_.size();
}

std::chrono::milliseconds GCStatisticsCollector::get_uptime() const {
    auto now = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time_);
    return duration;
}

// 性能分析
GCStatisticsCollector::Analysis GCStatisticsCollector::analyze_performance() const {
    Analysis analysis;

    std::lock_guard<std::mutex> lock(stats_mutex_);

    if (collection_history_.size() < 3) {
        analysis.memory_trend = Analysis::MemoryTrend::STABLE;
        analysis.memory_growth_rate = 0.0;
        analysis.is_gc_bottleneck = false;
        analysis.gc_overhead_percentage = 0.0;
        analysis.performance_grade = "N/A";
        return analysis;
    }

    // 内存趋势分析
    size_t recent_size = std::min(collection_history_.size(), size_t(10));
    double total_growth = 0.0;
    int growing_periods = 0;

    for (size_t i = 1; i < recent_size; ++i) {
        size_t current_idx = collection_history_.size() - i;
        size_t prev_idx = current_idx - 1;

        double heap_change = collection_history_[current_idx]->heap_size_after -
                          collection_history_[prev_idx]->heap_size_after;
        total_growth += heap_change;

        if (heap_change > 0) {
            growing_periods++;
        }
    }

    if (recent_size > 1) {
        analysis.memory_growth_rate = total_growth / (recent_size - 1);

        double growth_ratio = static_cast<double>(growing_periods) / (recent_size - 1);
        if (growth_ratio > 0.7) {
            analysis.memory_trend = Analysis::MemoryTrend::GROWING;
        } else if (growth_ratio < 0.3) {
            analysis.memory_trend = Analysis::MemoryTrend::SHRINKING;
        } else if (growth_ratio > 0.4 && growth_ratio < 0.6) {
            analysis.memory_trend = Analysis::MemoryTrend::FLUCTUATING;
        } else {
            analysis.memory_trend = Analysis::MemoryTrend::STABLE;
        }
    }

    // GC性能分析
    auto uptime_ms = get_uptime().count();
    if (uptime_ms > 0) {
        analysis.gc_overhead_percentage =
            (performance_stats_.total_gc_time_ms / uptime_ms) * 100.0;
    }

    analysis.is_gc_bottleneck =
        analysis.gc_overhead_percentage > config_.gc_bottleneck_threshold;

    // 性能评级
    if (analysis.gc_overhead_percentage < 2.0) {
        analysis.performance_grade = "A";
    } else if (analysis.gc_overhead_percentage < 5.0) {
        analysis.performance_grade = "B";
    } else if (analysis.gc_overhead_percentage < 10.0) {
        analysis.performance_grade = "C";
    } else if (analysis.gc_overhead_percentage < 15.0) {
        analysis.performance_grade = "D";
    } else {
        analysis.performance_grade = "F";
    }

    // 优化建议
    if (analysis.is_gc_bottleneck) {
        analysis.optimization_suggestions.push_back(
            "GC时间占比过高，考虑优化对象分配模式");
    }

    if (analysis.memory_trend == Analysis::MemoryTrend::GROWING) {
        analysis.optimization_suggestions.push_back(
            "内存持续增长，检查是否存在内存泄漏");
    }

    if (root_set_stats_.duplicate_removals > root_set_stats_.total_roots * 0.1) {
        analysis.optimization_suggestions.push_back(
            "根集重复对象过多，优化根对象管理");
    }

    if (performance_stats_.avg_gc_time_ms > 10.0) {
        analysis.optimization_suggestions.push_back(
            "GC平均耗时过长，考虑启用增量收集");
    }

    return analysis;
}

// 报告生成
void GCStatisticsCollector::print_summary() const {
    std::lock_guard<std::mutex> lock(stats_mutex_);

    std::cout << "\n=== GC统计摘要 ===" << std::endl;
    std::cout << "运行时间: " << get_uptime().count() << "ms" << std::endl;
    std::cout << "总收集次数: " << collection_history_.size() << std::endl;
    std::cout << "当前分配对象: " << allocation_stats_.current_allocations << std::endl;
    std::cout << "当前堆大小: " << allocation_stats_.current_bytes_allocated << " bytes" << std::endl;
    std::cout << "GC总耗时: " << performance_stats_.total_gc_time_ms << "ms" << std::endl;
    std::cout << "GC开销占比: " << std::fixed << std::setprecision(2)
              << (get_uptime().count() > 0 ?
                  (performance_stats_.total_gc_time_ms / get_uptime().count()) * 100.0 : 0.0)
              << "%" << std::endl;

    auto analysis = analyze_performance();
    std::cout << "性能评级: " << analysis.performance_grade << std::endl;
    std::cout << "================" << std::endl;
}

void GCStatisticsCollector::print_detailed_report() const {
    print_summary();
    print_allocation_report();
    print_performance_report();
    print_root_set_report();
    print_trend_analysis();
}

void GCStatisticsCollector::print_allocation_report() const {
    std::lock_guard<std::mutex> lock(stats_mutex_);

    std::cout << "\n=== 内存分配统计 ===" << std::endl;
    std::cout << "总分配次数: " << allocation_stats_.total_allocations << std::endl;
    std::cout << "总释放次数: " << allocation_stats_.total_deallocations << std::endl;
    std::cout << "当前分配对象: " << allocation_stats_.current_allocations << std::endl;
    std::cout << "峰值分配对象: " << allocation_stats_.peak_allocations << std::endl;

    std::cout << "\n按类型分配统计:" << std::endl;
    std::cout << "  字符串: " << allocation_stats_.string_allocations << std::endl;
    std::cout << "  列表: " << allocation_stats_.list_allocations << std::endl;
    std::cout << "  字典: " << allocation_stats_.dict_allocations << std::endl;
    std::cout << "  函数: " << allocation_stats_.function_allocations << std::endl;
    std::cout << "  其他: " << allocation_stats_.other_allocations << std::endl;

    std::cout << "\n内存使用统计:" << std::endl;
    std::cout << "  总分配字节: " << allocation_stats_.total_bytes_allocated << std::endl;
    std::cout << "  总释放字节: " << allocation_stats_.total_bytes_freed << std::endl;
    std::cout << "  当前堆大小: " << allocation_stats_.current_bytes_allocated << std::endl;
    std::cout << "  峰值堆大小: " << allocation_stats_.peak_bytes_allocated << std::endl;

    std::cout << "\n对象大小统计:" << std::endl;
    std::cout << "  平均大小: " << std::fixed << std::setprecision(2)
              << allocation_stats_.avg_object_size << " bytes" << std::endl;
    std::cout << "  最小大小: " << allocation_stats_.min_object_size << " bytes" << std::endl;
    std::cout << "  最大大小: " << allocation_stats_.max_object_size << " bytes" << std::endl;
    std::cout << "================" << std::endl;
}

void GCStatisticsCollector::print_performance_report() const {
    std::lock_guard<std::mutex> lock(stats_mutex_);

    std::cout << "\n=== GC性能统计 ===" << std::endl;
    std::cout << "总收集次数: " << performance_stats_.total_collections << std::endl;
    std::cout << "总GC耗时: " << std::fixed << std::setprecision(2)
              << performance_stats_.total_gc_time_ms << "ms" << std::endl;
    std::cout << "平均GC耗时: " << performance_stats_.avg_gc_time_ms << "ms" << std::endl;
    std::cout << "最短GC耗时: " << performance_stats_.min_gc_time_ms << "ms" << std::endl;
    std::cout << "最长GC耗时: " << performance_stats_.max_gc_time_ms << "ms" << std::endl;

    if (get_uptime().count() > 0) {
        std::cout << "GC频率: " << std::fixed << std::setprecision(2)
                  << performance_stats_.collections_per_second << " 次/秒" << std::endl;
    }

    std::cout << "\n增量收集统计:" << std::endl;
    std::cout << "  增量收集次数: " << performance_stats_.incremental_collections << std::endl;
    std::cout << "  总增量步骤: " << performance_stats_.total_incremental_steps << std::endl;
    std::cout << "  平均步骤耗时: " << performance_stats_.avg_incremental_step_time_ms << "ms" << std::endl;
    std::cout << "  增量效率: " << std::fixed << std::setprecision(2)
              << performance_stats_.incremental_efficiency << " 对象/毫秒" << std::endl;
    std::cout << "================" << std::endl;
}

void GCStatisticsCollector::print_root_set_report() const {
    if (!config_.enable_root_set_tracking) {
        std::cout << "\n根集统计已禁用" << std::endl;
        return;
    }

    std::lock_guard<std::mutex> lock(stats_mutex_);

    std::cout << "\n=== 根集统计 ===" << std::endl;
    std::cout << "总根对象数: " << root_set_stats_.total_roots << std::endl;
    std::cout << "唯一对象数: " << root_set_stats_.unique_objects << std::endl;

    std::cout << "\n按类型分布:" << std::endl;
    std::cout << "  栈对象: " << root_set_stats_.stack_roots << std::endl;
    std::cout << "  全局对象: " << root_set_stats_.global_roots << std::endl;
    std::cout << "  寄存器对象: " << root_set_stats_.register_roots << std::endl;
    std::cout << "  内部对象: " << root_set_stats_.internal_roots << std::endl;
    std::cout << "  用户对象: " << root_set_stats_.user_roots << std::endl;

    std::cout << "\n性能统计:" << std::endl;
    std::cout << "  平均添加时间: " << std::fixed << std::setprecision(3)
              << root_set_stats_.avg_add_time_us << "μs" << std::endl;
    std::cout << "  重复移除次数: " << root_set_stats_.duplicate_removals << std::endl;
    std::cout << "  批量操作次数: " << root_set_stats_.batch_operations << std::endl;

    if (!root_set_stats_.root_count_history.empty()) {
        std::cout << "\n根集历史趋势:" << std::endl;
        std::cout << "  当前: " << root_set_stats_.root_count_history.back() << std::endl;
        if (root_set_stats_.root_count_history.size() > 1) {
            size_t previous = root_set_stats_.root_count_history[
                root_set_stats_.root_count_history.size() - 2];
            int change = static_cast<int>(root_set_stats_.root_count_history.back()) - static_cast<int>(previous);
            std::cout << "  变化: " << (change >= 0 ? "+" : "") << change << std::endl;
        }
    }
    std::cout << "================" << std::endl;
}

void GCStatisticsCollector::print_trend_analysis() const {
    auto analysis = analyze_performance();

    std::cout << "\n=== 趋势分析 ===" << std::endl;

    const char* trend_names[] = {"稳定", "增长", "收缩", "波动"};
    std::cout << "内存趋势: " << trend_names[static_cast<int>(analysis.memory_trend)] << std::endl;
    std::cout << "内存增长率: " << std::fixed << std::setprecision(2)
              << analysis.memory_growth_rate << " bytes/次" << std::endl;

    std::cout << "\n性能评估:" << std::endl;
    std::cout << "  性能评级: " << analysis.performance_grade << std::endl;
    std::cout << "  GC开销: " << std::fixed << std::setprecision(2)
              << analysis.gc_overhead_percentage << "%" << std::endl;
    std::cout << "  性能瓶颈: " << (analysis.is_gc_bottleneck ? "是" : "否") << std::endl;

    if (!analysis.optimization_suggestions.empty()) {
        std::cout << "\n优化建议:" << std::endl;
        for (size_t i = 0; i < analysis.optimization_suggestions.size(); ++i) {
            std::cout << "  " << (i + 1) << ". " << analysis.optimization_suggestions[i] << std::endl;
        }
    }
    std::cout << "================" << std::endl;
}

// 私有辅助方法
void GCStatisticsCollector::update_performance_stats() {
    if (collection_history_.empty()) return;

    const auto& last_cycle = collection_history_.back();

    // 更新基本统计
    performance_stats_.total_collections = collection_history_.size();
    performance_stats_.total_gc_time_ms += last_cycle->duration_ms;

    // 计算平均、最小、最大GC时间
    double total_time = 0.0;
    double min_time = std::numeric_limits<double>::max();
    double max_time = 0.0;

    for (const auto& cycle : collection_history_) {
        total_time += cycle->duration_ms;
        min_time = std::min(min_time, cycle->duration_ms);
        max_time = std::max(max_time, cycle->duration_ms);
    }

    performance_stats_.avg_gc_time_ms = total_time / collection_history_.size();
    performance_stats_.min_gc_time_ms = min_time;
    performance_stats_.max_gc_time_ms = max_time;

    // 计算GC频率
    auto uptime_ms = get_uptime().count();
    if (uptime_ms > 0) {
        performance_stats_.collections_per_second =
            (collection_history_.size() * 1000.0) / uptime_ms;
        performance_stats_.avg_interval_ms = uptime_ms / collection_history_.size();
    }

    // 计算效率
    if (last_cycle->duration_ms > 0) {
        performance_stats_.objects_per_ms =
            (last_cycle->objects_marked + last_cycle->objects_swept) / last_cycle->duration_ms;
        performance_stats_.bytes_per_ms = last_cycle->bytes_swept / last_cycle->duration_ms;
    }

    if (last_cycle->mark_phase_ms > 0) {
        performance_stats_.mark_sweep_ratio =
            last_cycle->sweep_phase_ms / last_cycle->mark_phase_ms;
    }

    // 更新增量收集统计
    if (last_cycle->is_incremental) {
        performance_stats_.incremental_collections++;
        performance_stats_.total_incremental_steps++;
    }

    // 计算增量效率
    if (performance_stats_.total_incremental_steps > 0) {
        performance_stats_.incremental_efficiency =
            performance_stats_.objects_per_ms;
    }
}

void GCStatisticsCollector::reset_stats() {
    std::lock_guard<std::mutex> lock(stats_mutex_);

    collection_history_.clear();
    incremental_cycles_.clear();
    allocation_stats_ = AllocationStats{};
    performance_stats_ = PerformanceStats{};
    root_set_stats_ = RootSetStats{};

    start_time_ = std::chrono::high_resolution_clock::now();
    last_collection_time_ = start_time_;
}

void GCStatisticsCollector::reset_history() {
    std::lock_guard<std::mutex> lock(stats_mutex_);

    collection_history_.clear();
    incremental_cycles_.clear();

    root_set_stats_.root_count_history.clear();
    root_set_stats_.timestamp_history.clear();
}

void GCStatisticsCollector::set_config(const Config& new_config) {
    std::lock_guard<std::mutex> lock(stats_mutex_);
    config_ = new_config;
}

const GCStatisticsCollector::Config& GCStatisticsCollector::get_config() const {
    std::lock_guard<std::mutex> lock(stats_mutex_);
    return config_;
}

// GlobalGCStatistics实现
std::unique_ptr<GCStatisticsCollector> GlobalGCStatistics::instance_;
std::mutex GlobalGCStatistics::instance_mutex_;

GCStatisticsCollector& GlobalGCStatistics::get_instance() {
    std::lock_guard<std::mutex> lock(instance_mutex_);
    if (!instance_) {
        instance_ = std::make_unique<GCStatisticsCollector>();
    }
    return *instance_;
}

void GlobalGCStatistics::shutdown() {
    std::lock_guard<std::mutex> lock(instance_mutex_);
    instance_.reset();
}

bool GlobalGCStatistics::is_initialized() {
    std::lock_guard<std::mutex> lock(instance_mutex_);
    return instance_ != nullptr;
}

} // namespace viml